﻿using Md.Api.Entity.DapperModels.MdDB;
using Md.Api.Model.Manage.SysRole.Request;
using Md.Dapper.Repositories.Md;

namespace Md.Api.Service.Manage.SysRole;
/// <summary>
/// 添加系统角色服务
/// </summary>
public class InsertSysRoleService : ApiBase<RequestInsertSysRoleModel>
{
    /// <summary>
    /// 系统角色仓储
    /// </summary>
    public SysRoleRep sysRoleRep { get; set; }
    /// <summary>
    /// 系统角色菜单仓储
    /// </summary>
    public SysRoleMenuRep sysRoleMenuRep { get; set; }
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        var model = new SysRoleModel();

        model.RoleName = Parameter.RoleName;
        model.RoleKey = Parameter.RoleKey;
        model.DataScope = Parameter.DataScope;
        model.MenuCheckStrictly = Parameter.MenuCheckStrictly;
        model.DeptCheckStrictly = Parameter.DeptCheckStrictly;
        model.Status = Parameter.Status;
        model.DelFlag = "0";
        model.CreateBy = userKey?.ToString();
        model.CreateTime = DateTime.Now;

        var res = sysRoleRep.Insert(model);

        if (Convert.ToInt64(res) > 0)
        {
            // 添加角色拥有的菜单
            if (Parameter.MenuIds != null && Parameter.MenuIds.Length > 0)
            {
                // 删除角色拥有的菜单
                sysRoleMenuRep.DeleteMenuByRoleId(Convert.ToInt64(res));

                foreach (var menuId in Parameter.MenuIds)
                {
                    var roleMenuModel = new SysRoleMenuModel();
                    roleMenuModel.RoleId = Convert.ToInt64(res);
                    roleMenuModel.MenuId = menuId;

                    sysRoleMenuRep.Insert(roleMenuModel);
                }
            }

            Result.Data = sysRoleRep.GetSysRoleByRoleId(Convert.ToInt64(res));
        }
        else
        {
            Result.Data = res;
        }
    }
}

